
package com.ctg.sysmgr.sso.server.control.authentication;

import java.security.GeneralSecurityException;
import java.util.Collections;
import java.util.Map;

import javax.security.auth.login.FailedLoginException;
import javax.validation.constraints.NotNull;

import org.jasig.cas.authentication.HandlerResult;
import org.jasig.cas.authentication.PreventedException;
import org.jasig.cas.authentication.UsernamePasswordCredential;
import org.jasig.cas.authentication.handler.support.AbstractUsernamePasswordAuthenticationHandler;
import org.jasig.inspektr.common.web.ClientInfoHolder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.ctg.sysmgr.sso.server.dto.UserDTO;
import com.ctg.sysmgr.sso.server.service.sys.ISystemUserService;


public class SessionAcceptUserAuthenticationHandler extends AbstractUsernamePasswordAuthenticationHandler {

    /** The list of users we will accept. */
    @NotNull
    private Map<String, String> users;
    
    private ISystemUserService systemUserService;
    
    private final Logger logger = LoggerFactory.getLogger(this.getClass());
    /**
     * {@inheritDoc}
     **/
    @Override
    protected final HandlerResult authenticateUsernamePasswordInternal(final UsernamePasswordCredential credential)
            throws GeneralSecurityException, PreventedException {
    	Long userId = null;
    	String username = null;
    	String password = null;
    	String ip = null;
    	try {
    		UserDTO dto = new UserDTO();
	        username = credential.getUsername();
	        password = credential.getPassword();
	        dto.setSysCode(username);
	        dto.setPasswd(password);
	        ip = ClientInfoHolder.getClientInfo().getClientIpAddress();
	        logger.info("ip为{}，用户名为 {} 尝试登录验证中心。", ip, username);
        	userId = systemUserService.check(dto);
        } catch(GeneralSecurityException e) {
        	logger.info("ip为{}，用户名为{} 登录验证中心失败，原因是{}。", ip, username, e.getMessage()); 
        	throw e;
        } catch(Exception e) {
        	logger.error("ip为{}，用户名为{} 登录验证出错了，原因是{}。", ip, username, e.getMessage()); 
        	throw new FailedLoginException();
        }       
        logger.info("ip为{}，用户名为{} 登录验证中心成功，userId为{}。", ip, username, userId);
        return createHandlerResult(credential, this.principalFactory.createPrincipal(username), null);
    }

    /**
     * @param users The users to set.
     */
    public final void setUsers(final Map<String, String> users) {
        this.users = Collections.unmodifiableMap(users);
    }

	public final void setSystemUserService(final ISystemUserService systemUserService) {
		this.systemUserService = systemUserService;
	}

    
    
}
 